﻿@page "/"
@page "/category/{categoryId:int}"
@page "/search/{keywords}"
@inject INewsCategoryService _newsCategoryService
@inject INewsService _newsService
@inject NavigationManager _navigationManager
@inject MessageService _message
@using Whu.BLM.NewsSystem.Shared.Entity.Content;
@using Whu.BLM.NewsSystem.Client.Services


<Row Align="center">
    <Menu Mode=MenuMode.Horizontal>
        <MenuItem>
            <MenuLink Href="/">推荐</MenuLink>
        </MenuItem>
        @for (int i = 0; i < NewsCategories.Count; i++)
        {
            var newsCategory = NewsCategories[i];
            <AntDesign.MenuItem>
                <MenuLink Href=@($"/category/{newsCategory.Id}")>@newsCategory.Name</MenuLink>
            </AntDesign.MenuItem>
        }
    </Menu>
</Row>

<AntList DataSource="@News" ItemLayout="@ListItemLayout.Vertical" Loading="@IsLoading">
    <ChildContent>
        <ListItem Actions="@CreateNewsActions(context)">
            <ListItemMeta Description="@context.AbstractContent">
                <TitleTemplate>
                    <a href="@context.OringinUrl">【@context.NewsCategory.Name】@context.Title</a>
                </TitleTemplate>
            </ListItemMeta>
        </ListItem>
    </ChildContent>
    <LoadMore>
        @if (!IsLoading && HasMore)
        {
            <div class="loadmore-btn-content ">
                <Button OnClick="OnLoadMore">下一页</Button>
            </div>
        }
    </LoadMore>
</AntList>

<style>
        .loadmore-btn-content {
            text-align: center;
            margin-top: 12px;
            height: 32px;
            line-height: 32px;
        }
</style>

@code {

    [CascadingParameter]
    private Task<AuthenticationState> AuthenticationState { get; set; }

    [Parameter]
    public int? CategoryId { get; set; }

    [Parameter]
    public string Keywords { get; set; }

    private bool IsLoading { get; set; } = true;
    private bool HasMore { get; set; } = true;

    private IList<NewsCategory> NewsCategories = new List<NewsCategory>();
    private IList<News> News = new List<News>();

    private int _currentPage = 1;
    private int _pageSize = 10;

    private RenderFragment[] CreateNewsActions(News news)
    {
        if (AuthenticationState.Result.User.IsInRole("Admin"))
        {
            RenderFragment editAction = @<a href="/news/edit/@news.Id">编辑</a>;
            var onConfirm = new Func<Task>(async () => { await DeleteNews(news.Id); });
            RenderFragment deleteAction =
                @<Popconfirm Placement="@PlacementType.Bottom"
                             Title="确定删除这条新闻吗？"
                             OkText="确认"
                             CancelText="取消"
                             OnConfirm="onConfirm">
                    <Button Type="@ButtonType.Link" Danger>删除</Button>
                </Popconfirm>;
            return new[] {editAction, deleteAction};
        }
        return new RenderFragment[] {};
    }

    private async Task DeleteNews(int newsId)
    {
        await _newsService.DeleteNews(newsId);
        News.Remove(News.FirstOrDefault(x => x.Id == newsId));
        await _message.Info("删除成功!");
    }

    protected override async Task OnInitializedAsync()
    {
        NewsCategories = await _newsCategoryService.GetNewsCategoriesAsync();
    }

    protected override async Task OnParametersSetAsync()
    {
        _currentPage = 1;
        News = await FetchNews();
    }

    private async Task<IList<News>> FetchNews()
    {
        IsLoading = true;
        IList<News> newsList;
        if (string.IsNullOrEmpty(Keywords))
        {
            if (CategoryId == null)
                newsList = await _newsService.GetNewsListAsync(_currentPage, _pageSize);
            else
                newsList = await _newsService.GetNewsListAsync((int) CategoryId, _currentPage, _pageSize);
        }
        else
        {
            if (string.IsNullOrWhiteSpace(Keywords))
            {
                _navigationManager.NavigateTo("/");
                newsList = new List<News>();
            }
            else
            {
                newsList = await _newsService.SearchNewsAsync(Keywords, _currentPage, _pageSize);
            }
        }

        IsLoading = false;
        HasMore = newsList.Count == _pageSize;
        return newsList;
    }

    private async Task OnLoadMore()
    {
        _currentPage++;
        var news = await FetchNews();
        news.ForEach(x => News.Add(x));
    }

}